//
//  LocationViewController.m
//  Kokozu
//
//  Created by Bismarrck on 11-7-12.
//  Copyright 2011年 Tsinghua University. All rights reserved.
//

#import "LocationViewController.h"
#import "LocationMapViewController.h"
#import "UserDefault.h"
#import "UIViewController+BarItem.h"
#import "CustomTabBarViewController.h"

#define DEFAULT_ROW_HEIGHT 44
#define HEADER_HEIGHT 44



@interface LocationViewController ()

@property (nonatomic, retain) NSMutableArray* sectionInfoArray;
@property (nonatomic, assign) NSInteger openSectionIndex;
@property (nonatomic, assign) NSInteger uniformRowHeight;
@property (nonatomic, retain) NSArray *cityList;
@property (nonatomic, retain) NSArray *distList;

- (UIActionSheet *)actionSheetWithType:(SheetType)aType;
- (NSString *)sectionNameAtIndexPath:(NSIndexPath *)indexPath;  // origin indexpath

@end



@implementation LocationViewController

@synthesize commCircles;
@synthesize sectionInfoArray;
@synthesize openSectionIndex;
@synthesize lastIndexPath;
@synthesize uniformRowHeight;
@synthesize actionSheet = actionSheet_;
@synthesize dataPicker = dataPicker_;
@synthesize cityList;
@synthesize distList;
@synthesize delegate;


- (id)initWithStyle:(UITableViewStyle)style delegate:(id <LocationViewChangeDelegate>)aDelegate commCirles:(NSArray *)circles
{
    self = [super initWithStyle:style];
    if (self) {
        self.delegate = aDelegate;
        self.commCircles = circles;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)dismissModalViewController
{
    [self dismissModalViewControllerAnimated:YES];
    
    CustomTabBarViewController *sharedController = [CustomTabBarViewController sharedTabBarController];
   
    [sharedController.tabBar setHidden:NO];
}

- (void)loadSectionInfoArray
{
    NSMutableArray *circle_array = [[NSMutableArray alloc] init];
    for (int i = 0; i < 4; i++) {
        CommCircle *aCircle = [[CommCircle alloc] init];
        NSMutableArray *area_array = [[NSMutableArray alloc] init];
        for (int j = 0; j < 8; j++) {
            CommArea *area = [[CommArea alloc] init];
            area.areaName = [NSString stringWithFormat:@"子商圈%d", j];
            [area_array addObject:area];
            [area release];
        }
        aCircle.circleName = [NSString stringWithFormat:@"商圈%d", i];
        aCircle.commAreas = area_array;
        [area_array release];
        
        [circle_array addObject:aCircle];
        [aCircle release];
    }
    
    self.commCircles = circle_array;
    [circle_array release];
    
    if ((self.sectionInfoArray == nil) || ([self.sectionInfoArray count]+2 != [self numberOfSectionsInTableView:self.tableView])) {
		
        // For each play, set up a corresponding SectionInfo object to contain the default height for each row.
		NSMutableArray *infoArray = [[NSMutableArray alloc] init];
		
		for (CommCircle *commCircle in self.commCircles) {
			
			SectionInfo *sectionInfo = [[SectionInfo alloc] init];			
			sectionInfo.commCircle = commCircle;
			sectionInfo.open = NO;
			
			[infoArray addObject:sectionInfo];
			[sectionInfo release];
		}
		
		self.sectionInfoArray = infoArray;
        
		[infoArray release];
	}
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    // Set the nav bar title
    [self addTitleToNavigationBar:@"地理信息"];
    
    // Set the back/done baritem
    [self createBarItemOn:kNavBarItemSideLeft frame:kNavBarLeftItemFrame title:@"返回" target:self action:@selector(dismissModalViewController)];
    
    // Set the section info array
    [self loadSectionInfoArray];
    
    // Set the my geo info
    if ([[NSUserDefaults standardUserDefaults] valueForKey:@"my_city"]) {
        myCity_ = USER_DEFAULT_CITY;
        myDist_ = USER_DEFAULT_DISTRICT;
        myCommCircle_ = USER_DEFAULT_COMM_CIRCLE;
        myCommArea_ = USER_DEFAULT_COMM_AREA;
    }
    else {
        myCity_ = @"北京";
        myDist_ = @"海淀区";
    }
    
    // Set the list info
    self.cityList = [NSMutableArray arrayWithObjects:@"北京", nil];
    self.distList = [NSMutableArray arrayWithObjects:@"海淀区", @"朝阳区", @"西城区", @"东城区", @"丰台区", @"昌平区", nil];
    
    // Configure the table view 
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"background_light.png"]];
    self.tableView.sectionHeaderHeight = HEADER_HEIGHT;
    openSectionIndex = NSNotFound;
}


- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [commCircles count] + 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0 || section == 1) {
        return 1;
    }
    else {
        SectionInfo *sectionInfo = [self.sectionInfoArray objectAtIndex:section-2];
        NSUInteger numberInSection = [sectionInfo.commCircle.commAreas count];
        return sectionInfo.open ? numberInSection : 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
    }
    
    if (indexPath.section > 1) {     
        SectionInfo *sectionInfo = [self.sectionInfoArray objectAtIndex:indexPath.section - 2];
        cell.textLabel.text = [[sectionInfo.commCircle.commAreas objectAtIndex:indexPath.row] areaName];
        cell.detailTextLabel.text = @"";
        
    }
    else {
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        
        if (indexPath.section == 0) {
            cell.textLabel.text = @"城市";
            cell.detailTextLabel.text = myCity_;
        }
        else {
            cell.textLabel.text = @"行政区";
            cell.detailTextLabel.text = myDist_;
        }
    }
    // Configure the cell...
    
    cell.backgroundColor = self.view.backgroundColor;
    cell.selectionStyle = UITableViewCellSelectionStyleGray;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44.0f;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 44.0f;
}

- (void)pushToLocationView
{
    LocationMapViewController *mapViewController = [[LocationMapViewController alloc] initWithCommCircleMap:[UIImage imageNamed:@"1.png"] name:@"地图"];
    [self.navigationController pushViewController:mapViewController animated:YES];
    [mapViewController release];
}

-(UIView*)tableView:(UITableView*)tableView viewForHeaderInSection:(NSInteger)section 
{
    if (section == 0 || section == 1) {
        return nil;
    }

	SectionInfo *sectionInfo = [self.sectionInfoArray objectAtIndex:section-2];
    if (!sectionInfo.sectionHeaderView) {
		NSString *playName = sectionInfo.commCircle.circleName;
        sectionInfo.sectionHeaderView = [[[SectionHeaderView alloc] initWithFrame:CGRectMake(0.0, 0.0, self.tableView.bounds.size.width, HEADER_HEIGHT) title:playName section:section delegate:self] autorelease];
        
        UIButton *mapButton = [[UIButton buttonWithType:UIButtonTypeCustom] retain];
        [mapButton setFrame:CGRectMake(250, 5, 35, 35)];
        [mapButton setBackgroundImage:[UIImage imageNamed:@"mapbutton.png"] forState:UIControlStateNormal];
        [mapButton addTarget:self action:@selector(pushToLocationView) forControlEvents:UIControlEventTouchUpInside];
        [sectionInfo.sectionHeaderView addSubview:mapButton];
    }
    
    return sectionInfo.sectionHeaderView;
}

#pragma mark - Table view delegate


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        actionSheet_ = [self actionSheetWithType:PICKER_CITY];
    }
    else if (indexPath.section == 1) {
        actionSheet_ = [self actionSheetWithType:PICKER_DIST];
    }
    else {
        
        if (indexPath != lastIndexPath) {
            UITableViewCell *newCell = [self.tableView cellForRowAtIndexPath:indexPath];
            newCell.accessoryType = UITableViewCellAccessoryCheckmark;
            UITableViewCell *oldCell = [self.tableView cellForRowAtIndexPath:lastIndexPath];
            oldCell.accessoryType = UITableViewCellAccessoryNone;
            lastIndexPath = indexPath;
            [self.tableView beginUpdates];
            [self.tableView endUpdates];
        }
        
        // Write personal infomation into NSUserDefaults database
        SectionInfo *info = [self.sectionInfoArray objectAtIndex:indexPath.section - 2];
        myCommCircle_ = info.commCircle.circleName;
        myCommArea_ = [self.tableView cellForRowAtIndexPath:indexPath].textLabel.text;
        
        NSLog(@"%@", myCommCircle_);
        NSLog(@"%@", myCommArea_);
        
        USER_DEFAULT_COMM_CIRCLE_WRITE(myCommCircle_);
        USER_DEFAULT_COMM_AREA_WRITE(myCommArea_);
        
        NSLog(@"%@%@", USER_DEFAULT_COMM_CIRCLE, USER_DEFAULT_COMM_AREA);
        
        [delegate commAreaDidChanged];
    }
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath
{
    UIImage *mapImage = [UIImage imageNamed:@"1.png"];
    
    LocationMapViewController *mapViewController = [[LocationMapViewController alloc] initWithCommCircleMap:mapImage name:[self sectionNameAtIndexPath:indexPath]];
    [self.navigationController pushViewController:mapViewController animated:YES];
    [mapViewController release];
}

-(void)sectionHeaderView:(SectionHeaderView*)sectionHeaderView sectionOpened:(NSInteger)sectionOpened {
	
	SectionInfo *sectionInfo = [self.sectionInfoArray objectAtIndex:sectionOpened-2];
	
	sectionInfo.open = YES;
    
    /*
     Create an array containing the index paths of the rows to insert: These correspond to the rows for each quotation in the current section.
     */
    NSInteger countOfRowsToInsert = [sectionInfo.commCircle.commAreas count];
    NSMutableArray *indexPathsToInsert = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < countOfRowsToInsert; i++) {
        [indexPathsToInsert addObject:[NSIndexPath indexPathForRow:i inSection:sectionOpened]];
    }
    
    /*
     Create an array containing the index paths of the rows to delete: These correspond to the rows for each quotation in the previously-open section, if there was one.
     */
    NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
    
    NSInteger previousOpenSectionIndex = self.openSectionIndex;
    if (previousOpenSectionIndex != NSNotFound) {
		
		SectionInfo *previousOpenSection = [self.sectionInfoArray objectAtIndex:previousOpenSectionIndex-2];
        previousOpenSection.open = NO;
        [previousOpenSection.sectionHeaderView toggleOpenWithUserAction:NO];
        NSInteger countOfRowsToDelete = [previousOpenSection.commCircle.commAreas count];
        for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
            [indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:previousOpenSectionIndex]];
        }
    }
    
    // Style the animation so that there's a smooth flow in either direction.
    UITableViewRowAnimation insertAnimation;
    UITableViewRowAnimation deleteAnimation;
    if (previousOpenSectionIndex == NSNotFound || sectionOpened < previousOpenSectionIndex) {
        insertAnimation = UITableViewRowAnimationTop;
        deleteAnimation = UITableViewRowAnimationBottom;
    }
    else {
        insertAnimation = UITableViewRowAnimationBottom;
        deleteAnimation = UITableViewRowAnimationTop;
    }
    
    // Apply the updates.
    [self.tableView beginUpdates];
    [self.tableView insertRowsAtIndexPaths:indexPathsToInsert withRowAnimation:insertAnimation];
    [self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:deleteAnimation];
    [self.tableView endUpdates];
    self.openSectionIndex = sectionOpened;
    
    [indexPathsToInsert release];
    [indexPathsToDelete release];
}


-(void)sectionHeaderView:(SectionHeaderView*)sectionHeaderView sectionClosed:(NSInteger)sectionClosed {
    
    /*
     Create an array of the index paths of the rows in the section that was closed, then delete those rows from the table view.
     */
	SectionInfo *sectionInfo = [self.sectionInfoArray objectAtIndex:sectionClosed-2];
	
    sectionInfo.open = NO;
    NSInteger countOfRowsToDelete = [self.tableView numberOfRowsInSection:sectionClosed];
    
    if (countOfRowsToDelete > 0) {
        NSMutableArray *indexPathsToDelete = [[NSMutableArray alloc] init];
        for (NSInteger i = 0; i < countOfRowsToDelete; i++) {
            [indexPathsToDelete addObject:[NSIndexPath indexPathForRow:i inSection:sectionClosed]];
        }
        [self.tableView deleteRowsAtIndexPaths:indexPathsToDelete withRowAnimation:UITableViewRowAnimationTop];
        [indexPathsToDelete release];
    }
    self.openSectionIndex = NSNotFound;
}


- (UIToolbar *)actionSheetToolBar
{
    UIToolbar *actionToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 320.0f, 44.0f)];
    [actionToolBar setBarStyle:UIBarStyleDefault];
    
    NSMutableArray *barItems = [[NSMutableArray alloc] initWithCapacity:3];
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"选择" 
                                                                   style:UIBarButtonItemStyleDone 
                                                                  target:self
                                                                  action:@selector(selectionDone)];
    [barItems addObject:doneButton];
    [doneButton release];
    
    UIBarButtonItem *flexibleSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
    [barItems addObject:flexibleSpace];
    [flexibleSpace release];
    
    UIBarButtonItem *cancelButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" 
                                                                     style:UIBarButtonItemStyleBordered 
                                                                    target:self 
                                                                    action:@selector(selectionCancel)];
    [barItems addObject:cancelButton];
    [cancelButton release];
    
    actionToolBar.items = barItems;
    [barItems release];
    
    return actionToolBar;
}

- (UIActionSheet *)actionSheetWithType:(SheetType)aType
{
    UIActionSheet *actSheet = [[UIActionSheet alloc] initWithTitle:nil 
                                                          delegate:nil 
                                                 cancelButtonTitle:nil 
                                            destructiveButtonTitle:nil 
                                                 otherButtonTitles:nil, nil];
    actSheet.actionSheetStyle = UIActionSheetStyleDefault;
    
    picker_type_ = aType;
    
    CGRect frame = CGRectMake(0.0f, 40.0f, 0.0f, 0.0f);
    dataPicker_ = [[UIPickerView alloc] initWithFrame:frame];
    self.dataPicker.delegate = self;
    self.dataPicker.dataSource = self;
    self.dataPicker.showsSelectionIndicator = YES;
    [actSheet addSubview:self.dataPicker];
    
    UIToolbar *toolBar = [self actionSheetToolBar];
    [actSheet addSubview:toolBar];
    [toolBar release];
    
    [actSheet showInView:self.view];
    [actSheet setBounds:CGRectMake(0.0f, 0.0f, 320.0f, 485.0f)];
    
    return actSheet;
}

#pragma mark -
#pragma mark - Picker View Delegate

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 1;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component
{
    if (picker_type_ == PICKER_CITY) {
        return [self.cityList count];
    }
    else {
        return [self.distList count];
    }
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (picker_type_ == PICKER_CITY) {
        return [self.cityList objectAtIndex:row];
    }
    else {
        return [self.distList objectAtIndex:row];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (picker_type_ == PICKER_CITY) {
        myCity_ = [self pickerView:self.dataPicker titleForRow:row forComponent:0];
        [[NSUserDefaults standardUserDefaults] setValue:myCity_ forKey:@"my_city"];
        NSLog(@"%@", myCity_);
    }
    else {
        myDist_ = [self pickerView:self.dataPicker titleForRow:row forComponent:0];
        [[NSUserDefaults standardUserDefaults] setValue:myDist_ forKey:@"my_dist"];
    }
}

- (void)selectionCancel
{
    [self.actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

- (void)selectionDone
{   
    /*
    NSIndexPath *pathToReload;
    if (picker_type_ == PICKER_CITY) {
        [[NSUserDefaults standardUserDefaults] setValue:myCity_ forKey:@"my_city"];
        pathToReload = [NSIndexPath indexPathForRow:0 inSection:0];
    }
    else {
        [[NSUserDefaults standardUserDefaults] setValue:myDist_ forKey:@"my_dist"];
        pathToReload = [NSIndexPath indexPathForRow:0 inSection:1];
    }
    
    [self.tableView beginUpdates];
    [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:pathToReload] withRowAnimation:UITableViewRowAnimationNone];
    [self.tableView endUpdates];
    */
    [self.tableView reloadData];
    [self.actionSheet dismissWithClickedButtonIndex:0 animated:YES];
}

- (NSString *)sectionNameAtIndexPath:(NSIndexPath *)indexPath
{
    SectionInfo *info = [self.sectionInfoArray objectAtIndex:indexPath.section - 2];
    
    return info.commCircle.circleName;
}

@end
